package com.cynen.p42u.task;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Selenium 工具类,主要是通过自动打开网站,获取对应的cookie值.
 */
@Component
public class SeleniumTool {

    private static String initUrl="http://www.p42u.com/";

    // 启动后,将值写入到cookie文件中.
    // @Scheduled(cron = "0/1 * * * *")
    @Scheduled(initialDelay = 1000,fixedDelay = 3600*1000)
    public void getCookie() {
        // Chrome浏览器.需要下载指定的固定driver.
        System.setProperty("webdriver.chrome.driver","D:/develop/driver/chromedriver/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        long start = System.currentTimeMillis();
        driver.get(initUrl);
        // 隐式的等待,页面没有加载完成,就等待这个时间,停止加载.
        driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
        try {
            Thread.sleep(10000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        // 1.page1
        WebElement webElement = ((ChromeDriver) driver).findElementByLinkText("简体中文");
        System.out.println(webElement.getAttribute("href"));
        webElement.click();
        try {
            // page2
            driver.manage().timeouts().setScriptTimeout(6,TimeUnit.SECONDS);
            WebElement id = ((ChromeDriver) driver).findElementById("adultwarningprompt");
            WebElement elementByCssSelector = ((ChromeDriver) driver).findElementByCssSelector("div#adultwarningprompt input.btnAdultAgree");
            elementByCssSelector.click();
        }catch (NoSuchElementException e){
            System.out.println("没有弹出确认框...");
        }

        Set<Cookie> cookies = driver.manage().getCookies();
        for (Cookie cookie: cookies){
            if (cookie.getName().startsWith("cf_clearance")){
                System.out.println("我们需要的cookie:"+cookie.getValue());
                savecookie(cookie);
            }
        }
        // 关闭浏览器.
        driver.close();
        long end = System.currentTimeMillis();
        System.out.println("获取cookie总耗时" + (end - start)+" ms" );
        // driver.quit();

    }
    // 将cookie保存到指定的文件中.
    public static void savecookie(Cookie cookie){
        System.out.println("将最新的cookie存入到配置文件中");
        //读取文件.
        InputStream stream = SeleniumTool.class.getClassLoader().getResourceAsStream("config.properties");
        Properties prop = new Properties();
        try {
            prop.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取Cookie指定文件,并将获得的cookie值,写入到指定的配置文件中.
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(prop.getProperty("cookie_file_path")));
            String cookies = cookie.getName()+"="+cookie.getValue();
            bufferedWriter.write(cookies);
            bufferedWriter.flush();
            bufferedWriter.close();
            System.out.println("cookie已存入到配置文件");
        }catch (Exception e){
            System.out.println("cookie_file_path 配置文件异常");
        }
    }
}
